<?php

/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */

function _get_webform_interact_mapping($param) {
  /*
   * name: Interact Field
   * mapping: Corresponds to the value of relo.com
   * nid: 0 is public and >0 is private
   */
  $server = isset($param['server']) ? $param['server'] : '';
  $path = isset($param['path']) ? $param['path'] : '';
  $sid = isset($param['sid']) ? $param['sid'] : 0;
  $mapping = array();
  
  //------------- hard code------------------
  $sourceServer = $server;
  $sourceDatabasePath = $path;
  $sourceKey = uniqid().'_'.$sid;
  //---------------- end --------------------
  
  $mapping['WebEnquiryGeneralBO'] = array(
      
      //-------------------------- WebEnquiryGeneralBO ---------------------------------------
      array('name' => 'sourceServer', 'value' => $sourceServer, 'required' => true),
      array('name' => 'sourceDatabasePath', 'value' => $sourceDatabasePath, 'required' => true),
      array('name' => 'sourceKey', 'value' => $sourceKey, 'required' => true),
      array('name' => 'cds', 'value' => 'Sigma_CDS', 'required' => true),
      array('name' => 'customerType', 'value' => 'Sigma_', 'required' => true),
      array('name' => 'primaryOrigin', 'value' => 'Sigma_', 'required' => true),
      array('name' => 'originCity', 'value' => 'Sigma_', 'required' => true, 'mapping' => 'sending_work_city'),
      array('name' => 'originState'),
      array('name' => 'primaryDestination', 'value' => 'Sigma_', 'required' => true),
      array('name' => 'destinationState'),
      array('name' => 'destinationCity', 'value' => 'Sigma_', 'required' => true, 'mapping' => 'receiving_work_city'),
      array('name' => 'createdby'),
      array('name' => 'vip'),
      array('name' => 'moveConfidential'),
      array('name' => 'assignmentPhase', 'value' => 'Sigma_', 'required' => true),
      array('name' => 'valuableInformation'),
      
      array('name' => 'likelyServiceDate', 'value' => 'Sigma_', 'required' => true),
      array('name' => 'customerReference'),
      array('name' => 'cds', 'value' => 'Sigma_CDS', 'required' => true),
      array('name' => 'chargeCode'),
      array('name' => 'corpPhoneCountryCode'),
      array('name' => 'corpPhoneAreaCode'),
      array('name' => 'corporatePhoneNo'),
      array('name' => 'corpFaxCountryCode'),
      array('name' => 'corpFaxAreaCode'),
      array('name' => 'corporateFaxNo'),
      array('name' => 'possibleCorporate', 'mapping' => 'receiving_company_legal_entity2'),
      array('name' => 'insuranceBy'),
      array('name' => 'nationality'),
      array('name' => 'allowances'),
      //--------------------------------  end ---------------------------------
  );
  
  $mapping['WebEnquirySalesInfoBO'] = array(
      //-------------------------- WebEnquiryGeneralBO ---------------------------------------
      array('name' => 'leadSource', 'value' => '***', 'required' => true),
      array('name' => 'additionalCommentsOnLeadSource'),
      array('name' => 'expectedCompetitors'),
      array('name' => 'quotedVolumeWeight'),
      array('name' => 'salesRemarks'),
      array('name' => 'salesRegion'),
      array('name' => 'indicativeQuoteCurrency'),
      array('name' => 'indicativeQuoteRate'),
      //--------------------------------  end ---------------------------------
  );
  
  /*扩展功能，未确定*/
  $mapping['WebEnquirySalesInfoBO'][0]['child'] = array(
      //-------------------------- WebEnquiryGeneralBO leadSource---------------------------------------
      array('name' => 'quotedVolumeWeight', 'value' => '***', 'required' => true),
      array('name' => 'salesRemarks', 'value' => '***', 'required' => true),
      array('name' => 'salesRegion'),
      array('name' => 'indicativeQuoteCurrency'),
      array('name' => 'indicativeQuoteRate'),
      //--------------------------------  end ---------------------------------
  );
  $mapping['WebEnquirySalesInfoBO'][0]['attributes'] = array('name'=>'WebDependantImmigrationBO','version'=>"1.0");
  //end
  
  
  
  $mapping['WebClientBO'] = array(
      //-------------------------- WebClientBO ---------------------------------------
      array('name' => 'title', 'value' => '***', 'required' => true, 'mapping' => 'title'),
      array('name' => 'givenName', 'value' => '***', 'required' => true, 'mapping' => 'employee_first_name'),
      array('name' => 'familyName', 'value' => '***', 'required' => true, 'mapping' => 'employee_last_name'),


      array('name' => 'middleName'),
      array('name' => 'otherName'),
      array('name' => 'jobTitle'),
      array('name' => 'familySize'),
      array('name' => 'children'),
      array('name' => 'primaryEmail', 'mapping' => 'employee_last_name'),
      
      array('name' => 'secondaryEmail'),
      array('name' => 'workPhoneCountryCode'),
      array('name' => 'workPhoneAreaCode'),
      array('name' => 'workPhoneNo', 'mapping' => 'phone_work'),
      array('name' => 'homePhoneCountryCode'),
      array('name' => 'homePhoneAreaCode'),
      
      
      array('name' => 'homePhoneNo'),
      array('name' => 'mobilePhoneCountryCode'),
      array('name' => 'mobilePhoneAreaCode'),
      array('name' => 'mobilePhoneNo', 'mapping' => 'mobile_work'),
      array('name' => 'faxCountryCode'),
      array('name' => 'faxAreaCode'),
      array('name' => 'faxNo'),
      array('name' => 'transfereeGroup'),
      //--------------------------------  end ---------------------------------
  );
  
  //print_r($mapping);die;

  return $mapping;
}



function _get_all_arr($dataset) {
  $header_child = array(
      array('name' => 'MessageIdentification', 'attributes' => array('ID' => '6F331D04D6B51121482599A40013DF47', 'TimeStamp'=>'2012-11-09 11:37:24:00 TMZ', 'Expiry' => 'mm')),
      array('name' => 'ClientIdentification', 'attributes' => array('ID' => 'ClientID', 'UserID' => 'userid', 'Password' => 'pwd', 'authenticationToken' => 'encryptedtoken')),
      array('name' => 'MessageProcessing', 'attributes' => array('dataEncryption' => 'false', 'processortype' => 'NotifySCPassback', 'processedReceipt' => 'true', 'returnErrorToSender' => 'true')),
      array('name' => 'URLInfo', 'attributes' => array('httpServer' => 'intranet.crownrelo.com')),
  );
  
  $return = array(
      array('name' => 'Header', 'child' => $header_child),
      array('name' => 'DataSet', 'attributes' => $dataset['attributes'], 'child' => $dataset['child'] ),
  );
  return $return;
}
/** 
 * _get_dataset_child
 * @param array $mapping
 * @param string $group 
 * @param array $submission_data 
 **/
function _get_dataset_child($mapping, $group, $submission_data) {
  $dataset_child = array();
  if (isset($mapping[$group])) {
    $mapping = $mapping[$group];

    foreach ($mapping as $key => $val) {
      $row = array();
      if (isset($val['nid']) && $val['nid']) {
        if ($val['nid'] != $nid) {
          continue;
        }
      }

      if ($val['required']) {
        $row['name'] = $val['name'];
        $row['value'] = isset($submission_data[$val['mapping']]['value'][0]) ? $submission_data[$val['mapping']]['value'][0] : $val['value'];
        
        /*扩展功能，未确定*/
        if( isset($val['child']) && $val['child']){
          $row['child'] = $val['child'];
        };
        if( isset($val['attributes']) && $val['attributes']){
          $row['attributes'] = $val['attributes'];
        };
        //end
        
        $dataset_child[] = $row;
      } else if (isset($submission_data[$val['mapping']])) {
        $row['name'] = $val['name'];
        //$row['value'] = $val['value'];
        $row['value'] = isset($submission_data[$val['mapping']]['value'][0]) ? $submission_data[$val['mapping']]['value'][0] : '';
        $dataset_child[] = $row;
      }
      
    }
  }
  return $dataset_child;
}
function pg_find_cid_of_mapping_field($nid,$field_name){
    $query = db_select('webform_ext_system_mapping', 'c');
    $query->fields('c');
    $query->condition('c.nid', $nid );
    $query->condition('c.field_name', $field_name);
    $result = $query->execute()->fetchAssoc();
    return $result['cid'];
}
function pg_create_acount_spec_mapping($node,$submission){
    $nid=$node->nid;
    $submission_data=$submission->data;
    $mapping_value=pg_field_mapping($node,$submission_data);
    $ac_array = array(
    );
    $query = db_select('webform_ext_system_mapping','c');
    $query->fields('c');
    $query->condition('c.nid', $nid );
    $query->condition('c.field_obj', 'WebAccountSpecificInfoBO.WebAccountSpecificInfoDetailsBO' );
    $result = $query->execute();
    foreach ($result as $ac) {
        if(isset($mapping_value[$ac->field_name])){
            $value=$mapping_value[$ac->field_name];
        }  else {
            $value=$submission_data[$ac->cid]['value'][0];
        }
        if($ac->field_name=='Receiving Company/Legal Entity'&&$value=='0000|None of above|None'){
            continue;
        }
        $new_element=array(
            'label'=>$ac->field_name,
            'value'=>$value//$mapping_value[$ac->field_name],//$submission_data[$ac->cid]['value'][0],
        );
        array_push($ac_array, $new_element);
    }
    return $ac_array;
}
function pg_webform_interact_mapping($node,$submission){
    $sid=$submission->sid;
    $submission_data = $submission->data;
    $mapping_value=pg_field_mapping($node,$submission_data);
    //------------- hard code------------------
    if(isset($_REQUEST['sourceKey'])&$_REQUEST['sourceKey']!=''){
        $sourceKey=$_REQUEST['sourceKey'];
    }else{
        $sourceKey='PG_'.$mapping_value['primaryOrigin'].'_'.$sid;
    }
    //---------------- end --------------------
    $mapping = array(
        //-------------------------- WebEnquiryGeneralBO ---------------------------------------
        array(
            '@attributes' => array(  
                'name' => 'WebEnquiryGeneralBO',  
                'versionNo' => '1.0',  
            ),
            'sourceServer' => SOURCESERVER,
            'sourceDatabasePath' => SOURCEDATABASEPATH,
            'sourceKey' => $sourceKey,
            'customerType' => 'Corporate (Business Relocation)',
            'vip' => 'Standard',
            'confidential' => $mapping_value['confidential'],
            'assignmentPhase' => '',
            'valuableInformation' => '',
            'primaryOrigin' => $mapping_value['primaryOrigin'],
            'originState' => '',
            'originCity' => $mapping_value['originCity'],
            'primaryDestination' => $mapping_value['primaryDestination'],
            'destinationState' => '',
            'destinationCity' => $mapping_value['destinationCity'],
            'likelyServiceDate' => $mapping_value['likelyServiceDate'],
            'customerReference' => '',
            'cds' => $mapping_value['cds'],
            'chargeCode' => '',
            //'insuranceBy' => 'INSURANCE_BY_UNKNOWN(215)',
            //'nationality' => '',
        ),
        //-------------------------- WebEnquirySalesInfoBO ---------------------------------------
        array(
            '@attributes' => array(  
                'name' => 'WebEnquirySalesInfoBO',  
                'versionNo' => '1.0',  
            ),
            'leadSource' => "company policy/panel/recommended",
//            'additionalCommentsOnLeadSource' => '',
//            'expectedCompetitors' => '',
//            'quotedVolumeWeight' => '',
//            'salesRemarks' => '',
//            'salesRegion' => '',
//            'indicativeQuoteCurrency' => '',
//            'indicativeQuoteRate' => '',
        ),
        //-------------------------- WebAccountSpecificInfoBO ---------------------------------------
        array(
            '@attributes' => array(  
                'name' => 'WebAccountSpecificInfoBO',  
                'versionNo' => '1.0',  
            ),
            'DataObjectDetails' => array(
                '@attributes' => array(  
                'name' => 'WebAccountSpecificInfoDetailsBO',  
                'versionNo' => '1.0',  
                ),
                'DataObject' => pg_create_acount_spec_mapping($node,$submission),
            )
        ),
        //-------------------------- WebClientBO ---------------------------------------
        array(
            '@attributes' => array(  
                'name' => 'WebClientBO',  
                'versionNo' => '1.0',  
            ),
            'title' => $mapping_value['title'],
            'givenName' => $mapping_value['givenName'],
            'familyName' => $mapping_value['familyName'],
            'middleName' => '',
            'otherName' => '',
            'jobTitle' => '',
            'familySize' => '',
            'children' => '',
            'primaryEmail' => $mapping_value['primaryEmail'],
            'secondaryEmail' => $mapping_value['secondaryEmail'],
            'workPhoneCountryCode' => $mapping_value['workPhoneCountryCode'],
            'workPhoneAreaCode' => $mapping_value['workPhoneAreaCode'],
            'workPhoneNo' => $mapping_value['workPhoneNo'],
            'homePhoneCountryCode' => '',
            'homePhoneAreaCode' => '',
            'homePhoneNo' => '',
            'mobilePhoneCountryCode' => $mapping_value['mobilePhoneCountryCode'],
            'mobilePhoneAreaCode' => '',
            'mobilePhoneNo' => $mapping_value['mobilePhoneNo'],
            'faxCountryCode' => '',
            'faxAreaCode' => '',
            'faxNo' => '',
            'transfereeGroup' => 'DOMINO_PG_USERS', 
        ),
        //-------------------------- WebImmigrationTravelDocumentBO ---------------------------------------
        array(
            '@attributes' => array(  
                'name' => 'WebImmigrationTravelDocumentBO',  
                'versionNo' => '1.0',  
            ),
            'maritalStatus' => '',
            'gender' => $mapping_value['gender'],
        ),
        //-------------------------- WebAddressBO ---------------------------------------
        array(
            '@attributes' => array(  
                'name' => 'WebTempAddressBO',  
                'versionNo' => '1.0',  
            ),
             'DataObjectDetails' => array(
                '@attributes' => array(  
                'name' => 'WebAddressBO',  
                'versionNo' => '1.0',  
                ),
                'DataObject' => array(
                    array(
                        'country'=>$mapping_value['primaryOrigin'],
                        'city'=>$mapping_value['originCity'],
                        'addressType'=>'Pickup',
                        'currentAddress'=>0,
                    ),
                    array(
                        'country'=>$mapping_value['primaryDestination'],
                        'city'=>$mapping_value['destinationCity'],
                        'addressType'=>'Delivery',
                        'currentAddress'=>0,
                    ),
                )
            )
        ),
        //-------------------------- WebTempEnquiryManagingPartiesBO ---------------------------------------
        array(
            '@attributes' => array(  
                'name' => 'WebTempEnquiryManagingPartiesBO',  
                'versionNo' => '1.0',  
            ),
             'DataObjectDetails' => array(
                '@attributes' => array(  
                'name' => 'WebEnquiryManagingPartiesBO',  
                'versionNo' => '1.0',  
                ),
                'DataObject' => array(
                    array(
                        'role'=>'Booking',
                        'country'=>$mapping_value['booking_country'],
                        'city'=>$mapping_value['booking_city'],
                        'office'=>$mapping_value['booking_office'],
                        'owner'=>$mapping_value['booking_owner'],
                    ),
                    array(
                        'role'=>'Controlling',
                        'country'=>$mapping_value['controlling_country'],
                        'city'=>$mapping_value['controlling_city'],
                        'office'=>$mapping_value['controlling_office'],//'Connecticut (GMS)',
                        'owner'=>$mapping_value['controlling_owner'],
                    ),
                )
            )
        ), 
    );
    return $mapping;
}
function pg_field_mapping($node,$submission_data){
    $components = db_select('webform_component')
      ->fields('webform_component')
      ->condition('nid', $node->nid)
      ->orderBy('weight')
      ->orderBy('name')
      ->execute()
      ->fetchAllAssoc('cid', PDO::FETCH_ASSOC);
    // Do a little cleanup on each component.
    foreach ($components as $cid => $component) {
      $components[$cid]['nid'] = $node->nid;
      $components[$cid]['extra'] = unserialize($component['extra']);
      webform_component_defaults($components[$cid]);
    }
    //$components = $node->webform['components'];
    foreach ($components as $value) {
        //$value =  (array) $obj;
        if ($value['form_key'] == 'country_of_domestic_transfer') {
            foreach (explode("\n", $value['extra']['items']) as $each){
                $item=explode("|", $each);
                $country_array[$item[0]]=  trim($item[1]);
            }
            $cid_country_of_domestic_transfer=$value['cid'];//29
        }
        if ($value['form_key'] == 'confidential') {
            $confidential_array[0]='No';
            $confidential_array[1]='Yes At Origin and Destination';
            $cid_confidential=$value['cid'];//26
        }
        if ($value['form_key'] == 'sending_work_city') {
            $cid_sending_work_city=$value['cid'];
        }
        if ($value['form_key'] == 'please_specify_sending') {
            $cid_sending_work_city_specify=$value['cid'];//57
        }
        if ($value['form_key'] == 'receiving_work_city') {
            $cid_receiving_work_city=$value['cid'];//61
        }
        if ($value['form_key'] == 'please_specify_receiving') {
            $cid_receiving_work_city_specify=$value['cid'];
        }
        if ($value['form_key'] == 'phone_work') {
            $cid_phone_work=$value['cid'];//55
        }
        if ($value['form_key'] == 'mobile_work') {
            $cid_mobile_work=$value['cid'];//58
        }
        if ($value['form_key'] == 'relocation_effective_date') {
            $cid_relocation_effective_date=$value['cid'];//58
        }
        if ($value['form_key'] == 'title') {
            $title_array[1]="Miss";
            $title_array[2]="Mrs.";
            $title_array[3]="Mr.";
            $title_array[4]="Dr.";
            $cid_title=$value['cid'];//36
        }
        if ($value['form_key'] == 'employee_last_name') {
            $cid_employee_last_name=$value['cid'];//12
            $mapping_value['familyName']=str_replace(' ','',$submission_data[$cid_employee_last_name]['value'][0]);
        }
        if ($value['form_key'] == 'employee_first_name') {
            $cid_employee_first_name=$value['cid'];//13
            $mapping_value['givenName']=str_replace(' ','',$submission_data[$cid_employee_first_name]['value'][0]);
        }
        if ($value['form_key'] == 'email_address') {
            $cid_email_address=$value['cid'];//33
            $mapping_value['primaryEmail']=$submission_data[$cid_email_address]['value'][0];
        }
        if ($value['form_key'] == 'email_address_2') {
            $cid_email_address_2=$value['cid'];//67 or 68
            $mapping_value['secondaryEmail']=$submission_data[$cid_email_address_2]['value'][0];
        }
        //acount spec mapping setting
        if ($value['form_key'] == 'relocation_initiator_role') {
            foreach (explode("\n", $value['extra']['items']) as $each){
                $item=explode("|", $each);
                $relocation_initiator_role_array[$item[0]]=trim($item[1]);
            }
            $cid_relocation_initiator_role=$value['cid'];//22
        }
        if ($value['form_key'] == 'is_salary_change') {
            foreach (explode("\n", $value['extra']['items']) as $each){
                $item=explode("|", $each);
                $is_salary_change_array[$item[0]]=trim($item[1]);
            }
            $cid_is_salary_change=$value['cid'];//23
        }
        if ($value['form_key'] == 'relocation_type') {
            foreach (explode("\n", $value['extra']['items']) as $each){
                $item=explode("|", $each);
                $relocation_type_array[$item[0]]=trim($item[1]);
            }
            $cid_relocation_type=$value['cid'];//24
        }
        if ($value['form_key'] == 'sending_work_location_site') {
            $cid_sending_work_location_site=$value['cid'];//25
        }
        if ($value['form_key'] == 'salary_change_date') {
            $cid_salary_change_date=$value['cid'];//27
        }
        if ($value['form_key'] == 'receiving_work_location_site') {
            $cid_receiving_work_location_site=$value['cid'];//31
        }
        if ($value['form_key'] == 'is_relocation_initiator_acting_as_approver') {
            foreach (explode("\n", $value['extra']['items']) as $each){
                $item=explode("|", $each);
                $is_relocation_initiator_acting_as_approver_array[$item[0]]=trim($item[1]);
            }
            $cid_is_relocation_initiator_acting_as_approver=$value['cid'];//40
        }
        if ($value['form_key'] == 'split_family') {
            foreach (explode("\n", $value['extra']['items']) as $each){
                $item=explode("|", $each);
                $split_family_array[$item[0]]=trim($item[1]);
            }
            $cid_split_family=$value['cid'];//52
        }
        if ($value['form_key'] == 'relocation_initiator_phone_') {
            $cid_relocation_initiator_phone_=$value['cid'];//59
            $relocation_initiator_phone_array=explode("|", $submission_data[$cid_relocation_initiator_phone_]['value'][0]);
            $mapping_value['Relocation Initiator Phone #']='';
            if($relocation_initiator_phone_array[0]!=""){
                $mapping_value['Relocation Initiator Phone #']='+'.$relocation_initiator_phone_array[0].' ';
            }
            if($relocation_initiator_phone_array[1]!=""){
                $mapping_value['Relocation Initiator Phone #']=$mapping_value['Relocation Initiator Phone #'].$relocation_initiator_phone_array[1].' ';
            }
            if($relocation_initiator_phone_array[2]!=""){
                $mapping_value['Relocation Initiator Phone #']=$mapping_value['Relocation Initiator Phone #'].$relocation_initiator_phone_array[2];
            }
            if($relocation_initiator_phone_array[3]!=""){
                $mapping_value['Relocation Initiator Phone #']=$mapping_value['Relocation Initiator Phone #'].' ext '.$relocation_initiator_phone_array[3];
            }
        }
        if ($value['form_key'] == 'receiving_hr_manager_phone') {
            $cid_receiving_hr_manager_phone=$value['cid'];//60
            $receiving_hr_manager_phone_array=explode("|", $submission_data[$cid_receiving_hr_manager_phone]['value'][0]);
            $mapping_value['Receiving HR Manager Phone #']='';
            if($receiving_hr_manager_phone_array[0]!=""){
                $mapping_value['Receiving HR Manager Phone #']='+'.$receiving_hr_manager_phone_array[0].' ';
            }
            if($receiving_hr_manager_phone_array[1]!=""){
                $mapping_value['Receiving HR Manager Phone #']=$mapping_value['Receiving HR Manager Phone #'].$receiving_hr_manager_phone_array[1].' ';
            }
            if($receiving_hr_manager_phone_array[2]!=""){
                $mapping_value['Receiving HR Manager Phone #']=$mapping_value['Receiving HR Manager Phone #'].$receiving_hr_manager_phone_array[2];
            }
            if($receiving_hr_manager_phone_array[3]!=""){
                $mapping_value['Receiving HR Manager Phone #']=$mapping_value['Receiving HR Manager Phone #'].' ext '.$receiving_hr_manager_phone_array[3];
            }
        }
        if ($value['form_key'] == 'receiving_company_legal_entity2') {
            $cid_receiving_company_legal_entity2=$value['cid'];//62
            $legal_entity_key=  explode("|",$submission_data[$cid_receiving_company_legal_entity2]['value'][0]);
        }
        if ($value['form_key'] == 'company_code') {
            $cid_company_code=$value['cid'];
        }
        if ($value['form_key'] == 'company_name') {
            $cid_company_name=$value['cid'];
        }
        if ($value['form_key'] == 'is_the_employee_a_new_hire') {
            foreach (explode("\n", $value['extra']['items']) as $each){
                $item=explode("|", $each);
                $is_the_employee_a_new_hire_array[$item[0]]=trim($item[1]);
            }
            $cid_is_the_employee_a_new_hire=$value['cid'];//65
        }
        if ($value['form_key'] == 'is_the_spouse_partner_a_pg_employee') {
            foreach (explode("\n", $value['extra']['items']) as $each){
                $item=explode("|", $each);
                $is_the_spouse_partner_a_pg_employee_array[$item[0]]=trim($item[1]);
            }
            $cid_is_the_spouse_partner_a_pg_employee=$value['cid'];//69
        }
        if ($value['form_key'] == 'is_spouse_partner_also_being_transferred') {
            foreach (explode("\n", $value['extra']['items']) as $each){
                $item=explode("|", $each);
                $is_spouse_partner_also_being_transferred_array[$item[0]]=trim($item[1]);
            }
            $cid_is_spouse_partner_also_being_transferred=$value['cid'];//69
        }
        if ($value['form_key'] == 'function') {
            foreach (explode("\n", $value['extra']['items']) as $each){
                $item=explode("|", $each);
                $function_array[$item[0]]=trim($item[1]);
            }
            $cid_function=$value['cid'];//69
        }
        if ($value['form_key'] == 'if_cbd_please_provide_long_term_career_base') {
            $cid_if_cbd_please_provide_long_term_career_base=$value['cid'];//31
            $mapping_value['If CBD, please provide Long Term Career Base']=$submission_data[$cid_if_cbd_please_provide_long_term_career_base]['value'][0];
        }
        if ($value['form_key'] == 'legal_entity_which_employee_signed_their_contract_for') {
            $cid_legal_entity_which_employee_signed_their_contract_for=$value['cid'];//31
            $legal_entity_contract_key=  explode("|",$submission_data[$cid_legal_entity_which_employee_signed_their_contract_for]['value'][0]);
        }
        
    }
    $mapping_value['confidential']=$confidential_array[$submission_data[$cid_confidential]['value'][0]];
    $mapping_value['primaryOrigin']=$country_array[$submission_data[$cid_country_of_domestic_transfer]['value'][0]];
    $mapping_value['primaryDestination']=$country_array[$submission_data[$cid_country_of_domestic_transfer]['value'][0]];
    
    if($submission_data[$cid_sending_work_city]['value'][0]=='Other'){
        $mapping_value['originCity']=$submission_data[$cid_sending_work_city_specify]['value'][0];
    }else{
        $mapping_value['originCity']=$submission_data[$cid_sending_work_city]['value'][0];
    }
    if($submission_data[$cid_receiving_work_city]['value'][0]=='Other'){
        $mapping_value['destinationCity']=$submission_data[$cid_receiving_work_city_specify]['value'][0];
    }else{
        $mapping_value['destinationCity']=$submission_data[$cid_receiving_work_city]['value'][0];
    }
    $word_phone_array=explode("|",$submission_data[$cid_phone_work]['value'][0]);
    $mapping_value['workPhoneCountryCode']=$word_phone_array[0];
    $mapping_value['workPhoneAreaCode']=$word_phone_array[1];
    if($word_phone_array[3]!=""){
        $mapping_value['workPhoneNo']=$word_phone_array[2].$word_phone_array[3];
    }else{
        $mapping_value['workPhoneNo']=$word_phone_array[2];
    }
    $mapping_value['workPhoneNo']=  substr($mapping_value['workPhoneNo'], 0,10);
    $mobile_array=explode("|",$submission_data[$cid_mobile_work]['value'][0]);
    $mapping_value['mobilePhoneCountryCode']=$mobile_array[0];
    $mapping_value['mobilePhoneNo']=$mobile_array[1];
    if(strlen($mapping_value['mobilePhoneNo'])>=10){
        $mapping_value['mobilePhoneNo']=  substr($mapping_value['mobilePhoneNo'], 0,10);
    }
    $mapping_value['likelyServiceDate']=str_replace("-","/",$submission_data[$cid_relocation_effective_date]['value'][0]);
    $cds_domestic_ASIA=array('JA','IN','MY','CN','PH','ID','AU');
    $cds_domestic_EMEA=array('NL','DE','TR','PL','ES','CH','FR','AT','PK','RU','RO','HU','HR','CZ','SK','MA','GR','PT','IT','NL');
    $cds_domestic_LA=array('MX','CO','VE','AR','CL','BR');
    if (in_array($submission_data[$cid_country_of_domestic_transfer]['value'][0],$cds_domestic_ASIA)){
        $mapping_value['cds']='P&G Domestic ASIA';
    }else if (in_array($submission_data[$cid_country_of_domestic_transfer]['value'][0],$cds_domestic_EMEA)){
        $mapping_value['cds']='P&G Domestic EMEA';//'P&x xxxxxxxx xxEA';
    }else if (in_array($submission_data[$cid_country_of_domestic_transfer]['value'][0],$cds_domestic_LA)){
        $mapping_value['cds']='P&G Domestic LA';
    }
    $mapping_value['title']=$title_array[$submission_data[$cid_title]['value'][0]];
    if($submission_data[$cid_title]['value'][0]=="1"||$submission_data[$cid_title]['value'][0]=="2"){
        $mapping_value['gender']='Female';
    }else if($submission_data[$cid_title]['value'][0]=="3"){
        $mapping_value['gender']='Male';
    }
    $managing_party_obj = simplexml_load_string(variable_get('BB_ST_XML_ManagingParties'));
//    $managing_party_arr = xml2array($managing_party_obj);
    foreach ($managing_party_obj->country as $country) {
        $managing_party[(string)$country->country_code]['controlling_country']=(string)$country->controlling_country;
        $managing_party[(string)$country->country_code]['controlling_city']=(string)$country->controlling_city;
        $managing_party[(string)$country->country_code]['controlling_office']=(string)$country->controlling_office;
        $managing_party[(string)$country->country_code]['controlling_owner']=(string)$country->controlling_owner;
    }
    $mapping_value['booking_country']=(string)$managing_party_obj->booking_country;
    $mapping_value['booking_city']=(string)$managing_party_obj->booking_city;
    $mapping_value['booking_office']=(string)$managing_party_obj->booking_office;
    $mapping_value['booking_owner']=(string)$managing_party_obj->booking_owner;
    $mapping_value['controlling_country']=$managing_party[$submission_data[$cid_country_of_domestic_transfer]['value'][0]]['controlling_country'];
    $mapping_value['controlling_city']=$managing_party[$submission_data[$cid_country_of_domestic_transfer]['value'][0]]['controlling_city'];
    $mapping_value['controlling_office']=$managing_party[$submission_data[$cid_country_of_domestic_transfer]['value'][0]]['controlling_office'];
    $mapping_value['controlling_owner']=$managing_party[$submission_data[$cid_country_of_domestic_transfer]['value'][0]]['controlling_owner'];
    //account spec mapping
    $mapping_value['Relocation Initiator Role']=$relocation_initiator_role_array[$submission_data[$cid_relocation_initiator_role]['value'][0]];
    $mapping_value['Is there a Salary change planned prior to/upon Relocation?']=$is_salary_change_array[$submission_data[$cid_is_salary_change]['value'][0]];
    $mapping_value['Relocation Type']=$relocation_type_array[$submission_data[$cid_relocation_type]['value'][0]];
    $work_location_site_array=pg_get_location_site($submission_data[$cid_country_of_domestic_transfer]['value'][0]);
    $mapping_value['Sending Work Location']=$work_location_site_array[$submission_data[$cid_sending_work_location_site]['value'][0]];
    $mapping_value['If Yes, please confirm salary change effective date']=str_replace("-","/",$submission_data[$cid_salary_change_date]['value'][0]);
    $mapping_value['Relocation Effective Date']=str_replace("-","/",$submission_data[$cid_relocation_effective_date]['value'][0]);
    $mapping_value['Receiving Work Location']=$work_location_site_array[$submission_data[$cid_receiving_work_location_site]['value'][0]];
    $mapping_value['Is Relocation Initiator acting as Approver?']=$is_relocation_initiator_acting_as_approver_array[$submission_data[$cid_is_relocation_initiator_acting_as_approver]['value'][0]];
    $mapping_value['Split Family']=$split_family_array[$submission_data[$cid_split_family]['value'][0]];
    $legal_entity_arr=  pg_get_legal_entity_by_country($submission_data[$cid_country_of_domestic_transfer]['value'][0]);
//    $mapping_value['Receiving Company/Legal Entity']=str_replace("|","",$submission_data[$cid_receiving_company_legal_entity2]['value'][0]);
    if($legal_entity_key[0]){
        $mapping_value['Receiving Company/Legal Entity']=$legal_entity_arr[$legal_entity_key[0]];
    }else{
        $mapping_value['Receiving Company/Legal Entity']='';
    }
    if($mapping_value['Receiving Company/Legal Entity']=='0000|None of above|None'){
        unset($mapping_value['Receiving Company/Legal Entity']);
        $mapping_value['Company Code']=$submission_data[$cid_company_code]['value'][0];
        $mapping_value['Company Name']=$submission_data[$cid_company_name]['value'][0];
    }
    if($legal_entity_contract_key[0]){
        $mapping_value['Legal Entity which employee signed their contract for']=$legal_entity_arr[$legal_entity_contract_key[0]];
    }else{
        $mapping_value['Legal Entity which employee signed their contract for']='';
    }
    if($mapping_value['Legal Entity which employee signed their contract for']=='0000|None of above|None'){
        unset($mapping_value['Legal Entity which employee signed their contract for']);
    }
    
    $mapping_value['New Hire']=$is_the_employee_a_new_hire_array[$submission_data[$cid_is_the_employee_a_new_hire]['value'][0]];
    $mapping_value['Is the Spouse/Partner a P&G Employee?']=$is_the_spouse_partner_a_pg_employee_array[$submission_data[$cid_is_the_spouse_partner_a_pg_employee]['value'][0]];
    $mapping_value['Is Spouse/Partner also being transferred?']=$is_spouse_partner_also_being_transferred_array[$submission_data[$cid_is_spouse_partner_also_being_transferred]['value'][0]];
    $mapping_value['Function']=$function_array[$submission_data[$cid_function]['value'][0]];
    //$mapping_value['Relocation Initiator Last Name']='test';
    //For P&G Site Australia and New Zealand Country Mapping
    if($mapping_value['primaryOrigin']=='Australia & New Zealand'){
        $new_zealand_arr=array('Auckland Sales Office 4987','Auckland Office 5535','Bluff-Palmerston Plant 4878','Christchurch CBD 5834','Wellington Sales Office 5149','Ellerslie SO - Wella 7279');
        if (in_array($mapping_value['Sending Work Location'],$new_zealand_arr)){
            $mapping_value['primaryOrigin']='New Zealand';
            $mapping_value['primaryDestination']='New Zealand';
        }else{
            $mapping_value['primaryOrigin']='Australia';
            $mapping_value['primaryDestination']='Australia';
        }
    }else if($mapping_value['primaryOrigin']=='Russia'){
        $mapping_value['primaryOrigin']='Russian Federation';
        $mapping_value['primaryDestination']='Russian Federation';
    }else if($mapping_value['primaryOrigin']=='Romania, Bulgaria & Serbia'){
        $mapping_value['primaryOrigin']='Romania';
        $mapping_value['primaryDestination']='Romania';
    }
    return $mapping_value;
}
function pg_get_legal_entity_by_country($country) {
    $query = db_select('webform_company', 'c');
    $query->fields('c');
    $query->condition('c.country', $country);
    $result = $query->execute();  //print_r($result);die;
    foreach ($result as $each) {
        $company_array[$each->company_code]=$each->short_name.' - '.$each->company_code;
    }
    return $company_array;
}
function pg_get_location_site($country_code){
    $query = db_select('webform_location_site', 'c');
    $query->fields('c');
    $query->condition('c.country_code', $country_code);
    $result = $query->execute();  //print_r($result);die;
    foreach ($result as $each) {
        $site_array[$each->site_code]=$each->site_name.' '.$each->site_code;
    }
    return $site_array;
}
function _get_webform_interact_mapping2($node, $submission_data) {
  //$nid = $node->nid;
  
  $system_name = 'interact';
  $query = db_select('webform_component', 'c');
  $query->leftJoin('webform_ext_system_mapping', 'mp', 'c.cid = mp.cid and c.nid=mp.nid');
  $query->fields('c');
  $query->addField('mp', 'system_name', 'external_system_name');
  $query->addField('mp', 'field_obj', 'external_field_obj');
  $query->addField('mp', 'field_name', 'external_field_name');
  $query->addField('mp', 'mandatory', 'external_mandatory');
  $query->addField('mp', 'extra', 'external_extra');
  $query->addField('mp', 'uid', 'external_uid');
  $query->addField('mp', 'created', 'external_created');
  $query->addField('mp', 'updated', 'external_updated');
  $query->condition('c.nid', $node->nid );
  $query->condition('mp.system_name', $system_name );
  $result = $query->execute();  //print_r($result);die;
  //$mapping = array('WebEnquiryGeneralBO' => array(), 'WebEnquirySalesInfoBO' => array(), 'WebClientBO' => array());
  $mapping = array();
  if ($result) {
    foreach ($result as $key => $v) {
      
      //$mapping[] = $v;
      if ($v->mandatory == true or $v->external_mandatory == true or true) {
        //if( $v->external_field_obj=='WebEnquiryGeneralBO' || $v->external_field_obj=='WebEnquirySalesInfoBO' || $v->external_field_obj=='WebClientBO')
        if( trim($v->external_field_obj) != '')
        {
          
       
          $mapping[$v->external_field_obj][$v->cid]['name'] = $v->external_field_name;
          $mapping[$v->external_field_obj][$v->cid]['form_key'] = $v->form_key;
          

          // ------------------ display the value of component --------------------------------
          if ( isset($submission_data[$v->cid]['value']) && $submission_data[$v->cid]['value']) {
            $tag_value = null;
            $component_type = $node->webform['components'][$v->cid]['type'];
            $component = $node->webform['components'][$v->cid];
            $value = $submission_data[$v->cid]['value'];
            $display_function = '_webform_display_' . $component['type'];
            if (function_exists($display_function)) {
              $display = $display_function($component, $value, 'text');
              $display['#webform_component']=$component;
              $display['#theme_wrappers'] = array();
              $tag_value = str_replace("\n", ' ', drupal_render($display));
            }
            
            //-------------------------------
            $mapping[$v->external_field_obj][$v->cid]['field_type'] = $component_type;
            if($component_type == 'hidden'){
              $mapping[$v->external_field_obj][$v->cid]['value'] = $value[0];
            }else if($component_type == 'select'){
              $mapping[$v->external_field_obj][$v->cid]['value'] = $value[0];//$tag_value;
            }else{
              $mapping[$v->external_field_obj][$v->cid]['value'] = $tag_value;
            }
            //-------------------------------

          }
          // ---------------------- end display the value of component ----------------------------
          
          if( $v->form_key== 'initiation___assignment_move_start_date'){
            $mapping['likelyservicedate'] = $tag_value;
          }
          
          

        }

        
        
        
      }

    }
    
    //print_r($mapping);die;
  }
  return $mapping;
}



?>
